#include <signal.h>
//
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
//
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <unistd.h>
//
#include <time.h>
//

#define BUFSIZE 512
int s=0, s2=0;
//
void closeConnection(int a)
{
  if(s2!=0) close(s2);
  if(s!=0) close(s);
}
//
void printUsage()
{
  printf("usage: sendc_tester port\n");
}
//
int main(int argc, char *argv[]){
  int len;
  struct sockaddr_in  server, client;
  int backlog=5;
  char str[BUFSIZ];
  char rep[BUFSIZ];
  int optval=1;
  int n,rc;					

  if(argc<=1){
    printUsage();
    exit(1);
  }

  setbuf(stdout,NULL);
  setbuf(stderr,NULL);

  signal(SIGINT,closeConnection);
  signal(SIGTERM,closeConnection);

  if((s=socket(PF_INET,SOCK_STREAM,0))<0){
    perror("socket");
    exit(1);
  }
  //
  if((rc=setsockopt(s,SOL_SOCKET,SO_REUSEADDR,
		    (char *)&optval,sizeof(optval)))<0){
    perror("setsockopt");
    exit(1);
  }
  //
  memset((char *)&server, 0, sizeof(server));
  server.sin_len = sizeof(server);
  server.sin_family = PF_INET;
  server.sin_addr.s_addr  = htonl(INADDR_ANY);
  server.sin_port = htons(atoi(argv[1]));
  if(bind(s,(struct sockaddr *)&server,sizeof(server))<0){
    perror("bind");
    exit(1);
  }

  if(listen(s,backlog)<0){
    perror("listen");
    exit(1);
  }

  for(;;){
    printf("Waiting for connection...\n");
    memset((char *)&client, 0, sizeof(client));
    len = sizeof(client);
    if((s2=accept(s,(struct sockaddr *)&client,(socklen_t *)&len))<0){
      perror("accept");
      close(s);
      exit(1);
    }
    printf("Connected.\n");

    //
    do {
      printf("Waiting for message...\n");
      n=recv(s2,str,BUFSIZE,0);
      if(n<=0){
	if(n<0) perror("recv");
	close(s2);
	break;
      }
      str[n]='\0';// skip CR
      printf("GOT: '%s' [len=%d]\n",str,n);
      str[6]='\0';
      strcpy(rep,str);
      if((n&1)==0){
	strcat(rep,"NG");
      }else{
	strcat(rep,"OK");
      }
      rep[8]='\r';
      rep[9]='\n';
      rep[10]='\0';
      send(s2,rep,strlen(rep),0);
    } while(1);
  }
}
